﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;


namespace MP.Core.Library
{
    public class ProcessUtil
    {
        /// <summary>
        /// Chi cho form mo mot form duy nhat, neu da co form chay thi dong lai
        /// </summary>
        /// <param name="applicationName">Ten form</param>
        /// <param name="isKillFirstProcess">
        ///     True: Dong cac form da mo di, chi de lai form moi nhat vua mo len
        ///     False: Dong form vua mo, chi de lai form moi nhat
        /// </param>
        public static void RunSingleForm(string applicationName, bool isKillFirstProcess)
        {
            
            Process[] ps = Process.GetProcessesByName(applicationName);
            try
            {
                //se kill nhung form mo dau tien
                if (isKillFirstProcess)
                {
                    //sap xep cac process giam dan
                    for (int i = 0; i < ps.Length; i++)
                        for (int j = i + 1; j < ps.Length; j++)
                            if (ps[i].StartTime < ps[j].StartTime)
                            {
                                Process p = ps[i];
                                ps[i] = ps[j];
                                ps[j] = p;
                            }
                }
                //kill nhung form mo sau cung
                else
                {
                    //sap xep cac process tang dan
                    for (int i = 0; i < ps.Length; i++)
                        for (int j = i + 1; j < ps.Length; j++)
                            if (ps[i].StartTime > ps[j].StartTime)
                            {
                                Process p = ps[i];
                                ps[i] = ps[j];
                                ps[j] = p;
                            }
                }
                //xoa cac process, chi chua lai process duy nhat
                if (ps.Length > 0)
                {
                    for (int i = ps.Length - 1; i > 0; i--)
                        ps[i].Kill();
                }
            }
            catch (Exception ex)
            {
            }
        }
    }
}
